<template>
  <div>
    <FormPanel ref="from" :list="formList" @formChange="changeHandle" :isSubmitBtn="false" :collapse="false"
               :labelWidth="190"></FormPanel>

    <FilterTable ref="table"
                 :columns="columns"
                 :dataSource="tableList" height="auto"
                 :onColumnsChange="(columns) => (this.columns = columns)">
    </FilterTable>

    <div style="height: 47px"></div>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right',
      }"
    >
      <el-button @click="closeDrawer">关 闭</el-button>
    </div>
  </div>
</template>
<script>

import {
  getAmount,
  getDealerAddress,
  getDetail,
  getFiAccountType,
  getOrderDetailAmount,
  getOrderDetailType
} from '@/api/dealerSaleP/OrderManagement/OrderSubmission/index.js';
import {dictionary} from '@/utils/dictMixin';
import Cookies from 'js-cookie';
import moment from 'moment';

export default {
  mixins: [dictionary],
  components: {
  },
  props: ['rowData'],
  data() {
    this.saveData = null;
    return {
      formList: this.createdFrom(),
      columns: this.createdTable(),
      tableList: [],
      isaddCar: false,
      orderData: {},
      json: {},
      dealerCode: Cookies.get('ownerCode'),
      isSave: false,
      accountTypeList: [],
      selectList: [],
      isDisabled: true
    };
  },
  created() {
    // 初始化
    this.initOrder();
  },
  mounted() {
    this.table = this.$refs.table.$refs.pageTable;
  },
  methods: {
    createdFrom() {
      return [
        {
          type: 'BREAK_SPACE',
          label: '订单信息',
        },
        {
          type: 'INPUT',
          label: '订单编号',
          fieldName: 'orderNo',
          placeholder: '请输入',
          disabled: true,
        },
        {
          type: 'DATE',
          label: '订单年月',
          fieldName: 'orderYearMonth',
          disabled: true,
          placeholder: '请输入',
          dateType: 'month',
          initialValue: moment().format('YYYY-MM'),
        },
        {
          type: 'INPUT',
          label: '订单经销商',
          fieldName: 'orderDealer',
          placeholder: '请输入',
          disabled: true,
        },
        {
          type: 'SELECT',
          label: '订单类型',
          fieldName: 'orderType',
          disabled: true,
          placeholder: '请选择',
          itemList: this.createDictList('2105'),
          initialValue: 21051002, // 默认增补订单
        },
        {
          type: 'SELECT',
          label: '订单细分类型',
          fieldName: 'orderDetailType',
          placeholder: '请选择',
          itemList: [],
          disabled: true,
        },
        {
          type: 'SELECT',
          label: '订单状态',
          fieldName: 'orderStatus',
          disabled: true,
          placeholder: '请选择',
          itemList: this.createDictList('2104'),
          initialValue: 21041001, // 默认新建
        },
        {
          type: 'SELECT',
          label: '订单紧急度',
          fieldName: 'emergencyType',
          placeholder: '请选择',
          itemList: this.createDictList('2101'),
          initialValue: 21011001,
          rules: [{required: true, message: '请选择', trigger: 'change'}],
          disabled: true,
        },
        {
          type: 'SELECT',
          label: '运输方式',
          fieldName: 'transportType',
          placeholder: '请选择',
          itemList: this.createDictList('2409'),
          initialValue: 24091001,
          rules: [{required: true, message: '请选择', trigger: 'change'}],
          disabled: true,
        },
        {
          type: 'SELECT',
          label: '收车地址',
          fieldName: 'addressId',
          placeholder: '请选择',
          itemList: [],
          disabled: true,
          rules: [{required: true, message: '请选择', trigger: 'change'}],
          change: (value) => {
            this.orderAddressOnChange(value);
          },
        },
        {
          type: 'INPUT',
          label: '送达城市',
          fieldName: 'orderCity',
          placeholder: '请输入',
          disabled: true,
        },
        {
          type: 'INPUT',
          label: '联系人',
          fieldName: 'linkMan',
          placeholder: '请输入',
          disabled: true,
        },
        {
          type: 'INPUT',
          label: '联系电话',
          fieldName: 'linkPhone',
          placeholder: '请输入',
          disabled: true,
        },
        {
          type: 'INPUT_NUMBER',
          precision: 2,
          initialValue: 0.00,
          label: '资金可用余额',
          fieldName: 'totalFuelAmount',
          placeholder: '请选择',
          disabled: true,
        },
        {
          type: 'INPUT_NUMBER',
          precision: 2,
          initialValue: 0.00,
          label: '返利池可用余额',
          fieldName: 'singleRebateFuelAmount',
          disabled: true,
        },
        {
          type: 'INPUT_NUMBER',
          precision: 2,
          initialValue: 0.00,
          label: '本单返利使用金额',
          fieldName: 'rebateTotalAmount',
          disabled: true,
        },
        {
          type: 'INPUT_NUMBER',
          label: '实付总金额',
          fieldName: 'realPayTotalAmount',
          precision: 2,
          initialValue: 0.00,
          disabled: true,
        },
        {
          type: 'INPUT',
          label: '创建人',
          fieldName: 'createdName',
          placeholder: '请输入',
          disabled: true,
        },
        {
          type: 'INPUT',
          label: '创建时间',
          fieldName: 'createdAt',
          placeholder: '请输入',
          disabled: true,
        },
        {
          type: 'BREAK_SPACE',
          label: '车辆信息',
        },
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        {
          title: '物料编码',
          dataIndex: 'productCode',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '物料描述',
          dataIndex: 'productName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '提报数量',
          dataIndex: 'orderNum',
          sorter: true,
          filter: true,
          filterType: 'input',
          width: 100,
          editable: false,
          editType: 'number',
          editRequired: true,
          defaultEditable: true,
          editPattern: /^[1-9]\d*$/,
          summation: true,
          rules: [{required: true, message: '请填写正整数', trigger: 'blur'}],
        },
        {
          title: '车辆用途',
          dataIndex: 'vehicleUse',
          width: 150,
          align: 'center',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: false,
          editType: 'select',
          editRequired: true,
          rules: [{required: true, message: '请选择', trigger: 'change'}],
          render: (p) => {
            return (
              <el-select
                size="mini"
                v-model={p.row.vehicleUse}
                placeholder="请选择"
                disabled
              >
                {this.createDictList('2102').map((item) => (
                  <el-option key={item.value} label={item.text} value={item.value}/>
                ))}
              </el-select>
            );
          },
        },
        {
          title: '资金类型',
          dataIndex: 'fundType',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: false,
          editType: 'select',
          editRequired: true,
          rules: [{required: true, message: '请选择', trigger: 'change'}],
          render: (p) => {
            return (
              <el-select
                size="mini"
                v-model={p.row.fundType}
                required
                placeholder="请选择"
                disabled
              >
                {this.accountTypeList.map((item) => (
                  <el-option key={item.accountTypeId} label={item.accountTypeName} value={item.accountTypeId}/>
                ))}
              </el-select>
            );
          },
        },
        {
          title: '采购价格',
          dataIndex: 'afterDiscountAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '市场指导价',
          dataIndex: 'singleAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '现金折让',
          dataIndex: 'discountAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '建店返利',
          dataIndex: 'buildRebateAmount',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '是否使用返利',
          dataIndex: 'isRebate',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: false,
          editType: 'select',
          editRequired: true,
          rules: [{required: true, message: '请选择', trigger: 'change'}],
          render: (p) => {
            return (
              <el-select
                size="mini"
                v-model={p.row.isRebate}
                placeholder="请选择"
                disabled
              >
                {this.createDictList('1004').map((item) => (
                  <el-option key={item.value} label={item.text} value={item.value}/>
                ))}
              </el-select>
            );
          },
        },
        {
          title: '返利池返利',
          dataIndex: 'singleRebateAmount',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车系',
          dataIndex: 'seriesName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '车型',
          dataIndex: 'modelName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '配置',
          dataIndex: 'packageName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '选装',
          dataIndex: 'optionName',
          align: 'center',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '内饰',
          dataIndex: 'trimName',
          align: 'center',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '外饰',
          dataIndex: 'colorName',
          align: 'center',
          sorter: true,
          filter: true,
          filterType: 'input',
        }
      ];
    },
    changeHandle(val) {
      this.saveData = val;
    },
    /**
     * 初始化
     * @returns {Promise<void>}
     */
    async initOrder() {
      this.isSave = true;
      // 判断是否编辑
      if (this.rowData) {
        // 通过订单id查询订单和订单明细数据
        let res = await getDetail({orderId: this.rowData.orderId});
        if (res.resultCode === 200) {
          for (let i in res.data) {
            this.formList.map(x => {
              if (i === x.fieldName) {
                x.initialValue = res.data[i];
              }
            });
          }
          this.tableList = res.data.detailDTOList || [];
          let orderAmountDatas = await getOrderDetailAmount(this.dealerCode, this.tableList);
          if (orderAmountDatas.resultCode === 200) {
            this.tableList.forEach(car => {
              const orderAmount = orderAmountDatas.data.find(({productCode}) => productCode === car.productCode);
              if (orderAmount) {
                car.orderAmount = orderAmount;
              }
            });
          }
        }
      }
      // 订单细分类型
      this.getOrderDetailType();
      // 收车地址
      this.getDealerAddress();
      // 经销商资金
      this.getAmountDetail();
      // 资金类型
      this.getFiAccountType();

      this.isSave = false;
    },
    /**
     * 获取订单细分类型
     */
    async getOrderDetailType() {
      let list = await getOrderDetailType({isAvailable: 10041001});
      this.formList.map((x) => {
        if (x.fieldName === 'orderDetailType') {
          x.itemList = list.data.map((x) => ({text: x.subName, value: x.subId}));
        }
      });
    },
    /**
     * 获取收车地址
     */
    async getDealerAddress() {
      let res = await getDealerAddress({dealerCode: this.dealerCode});
      if (res.resultCode === 200) {
        this.addressList = res.data;
        this.formList.map((x) => {
          if (x.fieldName === 'addressId') {
            x.itemList = this.addressList.map((x) => ({
              text: `${x.detaildAddress}${x.addressProperty === 60351001 ? '（主店）' : ''}`,
              value: x.addressId,
              addressProperty: x.addressProperty
            }));
          }
        });
      }
    },
    /**
     * 选择收车地址事件
     */
    async orderAddressOnChange(value) {
      this.addressList.map((addr) => {
        if (addr.addressId === value) {
          this.formList.find(item => item.fieldName === 'orderCity').initialValue = addr.cityName;
          this.formList.find(item => item.fieldName === 'linkMan').initialValue = addr.linkMan;
          this.formList.find(item => item.fieldName === 'linkPhone').initialValue = addr.linkPhone;
        }
      });
    },
    /**
     * 查询经销商资金可用余额和返利池可用余额
     */
    async getAmountDetail() {
      let resList = await getAmount({dealerCode: this.dealerCode});
      if (resList.resultCode === 200) {
        this.formList.find((x) => x.fieldName === 'totalFuelAmount').initialValue = resList.data.totalFuelAmount;
        this.formList.find((x) => x.fieldName === 'singleRebateFuelAmount').initialValue = resList.data.singleRebateFuelAmount;
      }
    },
    /**
     * 查询资金类型
     */
    async getFiAccountType() {
      let obj = await getFiAccountType({dealerCode: this.dealerCode});
      if (obj.resultCode === 200) {
        this.accountTypeList = obj.data;
      }
    },

    async closeDrawer() {
      this.$emit('close');
    },
    changeValueNum(a) {
      if (!a || isNaN(a)) {
        return 0;
      } else {
        return a;
      }
    },
    formatNumber(val) {
      return Number(val).toFixed(2);
    },
  },
};
</script>
<style lang="less">
.discount {
  text-decoration: underline;
  color: #d1291a;
  cursor: pointer;
}
</style>
